package heima_bixiangdong.itcast;

/**
 * 线程任务 --- 并发卖票(当然是票自己最清楚自己还剩多少张)(多个线程需要并发执行这个卖票任务)
 */
public class Ticket_1 implements Runnable{

    // 票的数量
    private int tickets;

    public Ticket_1(int tickets) {
        this.tickets = tickets;
    }

    public int getTickets() {
        return tickets;
    }

    public void setTickets(int tickets) {
        this.tickets = tickets;
    }
    private Object object = new Object();

    // 避免多线程并发执行出现安全问题，增加同步操作
    @Override
    public void run() {
        while (true){
            synchronized (object){
                if(tickets>0){
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "..." + tickets--);
                }
            }
        }
    }
}
